﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Apollo.Core;
using System.Xml.Linq;
using Apollo.Modules.Salary;

namespace Apollo.Website
{
    public partial class AddTransaction : System.Web.UI.Page
    {
        protected Transaction obj = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.Request["ObjectId"]) && this.Request["ObjectId"] != "0" && this.Request["ObjectId"] != "-1")
                this.Response.Redirect("/Edit.aspx?EntityId=87&ObjectId="
                    + this.Request["ObjectId"]
                    + "&dummy=" + DateTime.Now.Ticks.ToString());

            this.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            FormGroup group = FormGroup.FromXml(XElement.Parse(@"
  <group type=""Properties"" displayname=""General"">

    <property col=""0"" row=""0"" type=""Required"">Employee</property>
    <property col=""1"" row=""0"" type=""Required"">Definition</property>
    <property col=""2"" row=""0"" type=""Required"">AccountingMonth</property>


    <property col=""0"" row=""1"" type=""Required"">GrossValue</property>
    <property col=""1"" row=""1"" type=""Required"">Currency</property>
    <property col=""2"" row=""1"" type=""Normal"">CostCenter</property>
  </group>
"), new Form() { 
          AppendTabs = false
        , Entity = Apollo.Application.Meta<Entity>().SingleOrDefault<Entity>(en => en.Name == "Transaction")
    });

            foreach (FormItem item in group.Items) {
                if (item.Projection.ProjectionPath == "Currency")
                    item.DefaultValue = "1020122897";
                else if (item.Projection.ProjectionPath == "AccountingMonth")
                    item.DefaultValue = Apollo.Application.CurrentSession.QueryOver<AccountingMonth>()
                        .Where(m => m.IsClosed == false)
                        .Take(1).SingleOrDefault().Id.ToString();
                else if (item.Projection.ProjectionPath == "Employee" && !string.IsNullOrEmpty(this.Request["ID_Employee"]))
                    item.DefaultValue = this.Request["ID_Employee"];
            }

            FormGroupTransacion.Group = group;
            FormGroupTransacion.TargetObject = null;

        }


        protected ActionContext Save()
        {
            obj = new Transaction();

            ActionContext context = new ActionContext();

            foreach (ActionMessage msg in FormGroupTransacion.Save(obj).Messages)
                context.AddMessage(msg);
            

            if (context.State == ActionState.Failed)
            {
                foreach (ActionMessage msg in context.Messages)
                    this.MessageList.AddMessage(msg);

                return context;
            }

            obj.InsertBy = this.User.Identity.Name;
            obj.InsertDate = DateTime.Now;

            TransactionDefinition d = Apollo.Application.CurrentSession.Get<TransactionDefinition>(obj.Definition.Id);
            obj.Name = d.Name;
            
            context = Apollo.Application.Current.Save(obj);

            foreach (ActionMessage msg in context.Messages)
                this.MessageList.AddMessage(msg);

            if (context.State == ActionState.Succesful)
            {
                LinkButtonSave.Visible = false;
                LinkButtonSaveNew.Visible = false;
                LinkButtonSaveClose.Visible = false;
            }

            return context;
        }

        protected void ButtonSave_Click(object sender, EventArgs e)
        {
            this.Save();
        }

        protected void ButtonSaveNew_Click(object sender, EventArgs e)
        {
            if (this.Save().State == ActionState.Succesful)
            {
                string qsOther = "";

                if (!string.IsNullOrEmpty(this.Request["property"]))
                {
                    qsOther = "&property=" + this.Request["property"]
                        + "&belongsTo=" + this.Request["belongsTo"];
                }

                this.Response.Redirect("/AddTransaction.aspx");
            }
        }

        protected void ButtonSaveClose_Click(object sender, EventArgs e)
        {
            if (this.Save().State == ActionState.Succesful)
            {
                this.LiteralJS.Text = @"
<script type=""text/javascript"">
    $(document).ready(function () {
        ModalReturn(-1);
    });
</script>
";
            }
        }

        protected void ButtonSaveNewEmployee_Click(object sender, EventArgs e)
        {
            if (this.Save().State == ActionState.Succesful)
            {
                this.Response.Redirect("/AddTransaction.aspx?ID_Employee=" + obj.Employee.Id.ToString());
            }
        }

    }
}